package dao

import (
	"fmt"
	"gin-mvc/pkg/setting"
	"github.com/jinzhu/gorm"
	"time"
)

func InitMysqlPool() *gorm.DB {
	var (
		dbType, dbName, user, password, host, tablePrefix string
	)

	dbType = setting.DatabaseSetting.Type
	dbName = setting.DatabaseSetting.Name
	user = setting.DatabaseSetting.User
	password = setting.DatabaseSetting.Password
	host = setting.DatabaseSetting.Host
	tablePrefix = setting.DatabaseSetting.TablePrefix

	dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", user, password, host, dbName)
	db, err1 := gorm.Open(dbType, dsn)
	if err1 != nil {
		panic("连接数据库失败：" + err1.Error())
		return nil
	}

	if err := db.DB().Ping(); err != nil {
		panic("数据库连接失败")
	}

	// 使用表前缀
	gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		return tablePrefix + defaultTableName
	}

	// 数据库连接池设置
	db.SingularTable(true) //严格匹配关闭
	db.DB().SetMaxIdleConns(5)
	db.DB().SetMaxOpenConns(100)
	db.DB().SetConnMaxLifetime(time.Hour * 2)

	return db
}
